//
//  TCM_InformationViewController.swift
//  TCM_TradingProject
//
//  Created by 吕春海 on 2018/8/17.
//  Copyright © 2018年 lvchunhai. All rights reserved.
//

import UIKit
import FWSegmentedControl

class TCM_InformationViewController: TCM_BaseViewController, UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,CycleViewDelegate {
    /// 是否点击了Segmented的滑块
    var isClickedSegmented = false
    /// Segmented的滑块起始页
    var startPage = 0
    
    var informationTableview:UITableView!
    
    let sectionTitles:[String] = ["推荐", "市场快讯", "地产快讯", "品种快讯", "产业快讯", "中药材快讯"]
    let informationArry = [["市场盘点（第三期）：香料收付失地", "专家传最近西洋参可能会大幅度涨价西洋参大幅度涨价，你怎么看？", "安国市场黄精行情在坚挺中运行，有效缓解中药市场。"], ["市场盘点", "本地资讯", "药品分析"], ["刚刚", "30分钟前", "3小时前"], ["500", "1882", "2k"], ["huangjing.jpg", "huangjing.jpg", "huangjing.jpg"]]
    
    private lazy var segmentedControl: FWSegmentedControl = {
        
        let segmentedControl = FWSegmentedControl.segmentedWith(scType: SCType.text, scWidthStyle: SCWidthStyle.fixed, sectionTitleArray: nil, sectionImageArray: nil, sectionSelectedImageArray: nil, frame: CGRect(x: 0, y: Int(TCM_NavBarHeight()), width: Int(TCM_ScreenWidth), height: 44))
        
        segmentedControl.sectionTitleArray = sectionTitles
        segmentedControl.scSelectionIndicatorStyle = .contentWidthStripe
        
        segmentedControl.selectionIndicatorHeight = 2
        segmentedControl.selectionIndicatorColor = TCM_HexRGB(0x693C26)
        
        segmentedControl.titleTextAttributes = [NSAttributedStringKey.foregroundColor: TCM_HexRGB(0x3B3B3B), NSAttributedStringKey.font : UIFont.systemFont(ofSize: CGFloat(14))]
        segmentedControl.selectedTitleTextAttributes = [NSAttributedStringKey.foregroundColor: TCM_HexRGB(0x693C26), NSAttributedStringKey.backgroundColor: UIColor.clear, NSAttributedStringKey.font: UIFont.systemFont(ofSize: CGFloat(14))]
        return segmentedControl
    }()
    
    lazy var scrollView: UIScrollView = {
        
        let scrollView = UIScrollView.init(frame: CGRect(x: 0, y: self.segmentedControl.frame.maxY, width: TCM_ScreenWidth, height: TCM_ScreenHeight-self.segmentedControl.frame.maxY))
        scrollView.backgroundColor = UIColor.clear
        scrollView.isPagingEnabled = true
        scrollView.delegate = self
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = false
        scrollView.contentSize = CGSize(width: self.view.bounds.width * CGFloat(sectionTitles.count), height: self.segmentedControl.frame.height)
        scrollView.scrollRectToVisible(CGRect(x: 0, y: 0, width: TCM_ScreenWidth, height: scrollView.frame.height), animated: false)
        return scrollView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.title = "资讯"
        self.view.addSubview(self.segmentedControl)
        self.view.addSubview(self.scrollView)

        self.segmentedControl.indexChangeBlock = { [weak self] index in
            self?.isClickedSegmented = true
            self?.scrollView.scrollRectToVisible(CGRect(x: (self?.view.bounds.width)! * CGFloat(index), y: 0, width: (self?.view.bounds.width)!, height: (self?.scrollView.frame.height)!), animated: true)
        }
        

        self.scrollView.addSubview(self.setupUITableView(index: 0))


    }

    func addChildViewControllerWithChildVC(childVC:UIViewController, parentVC:UIViewController) {
        parentVC.addChildViewController(childVC)
        parentVC.didMove(toParentViewController: childVC)
        parentVC.view .addSubview(childVC.view)
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

extension TCM_InformationViewController {
    
    func setupUITableView(index: Int) -> UITableView {
        
        self.informationTableview = UITableView(frame: CGRect(x: 0, y: 0, width: TCM_ScreenWidth, height: TCM_ScreenHeight - TCM_NavBarHeight() - 44 - TCM_SafeBottomAndTabbarHeight()), style:.grouped)
        self.informationTableview.backgroundColor = TCM_HexRGB(0xF0F0F0)
        self.informationTableview.separatorStyle = UITableViewCellSeparatorStyle.none
        self.informationTableview.showsVerticalScrollIndicator = false
        self.informationTableview.delegate = self
        self.informationTableview.dataSource = self
        
        let cycleView : CycleView = CycleView(frame: CGRect(x: 0, y: TCM_NavBarHeight() + 44, width: TCM_ScreenWidth, height: 188))
        cycleView.delegate = self
        cycleView.mode = .scaleAspectFill
        //本地图片测试--加载网络图片,请用第三方库如SDWebImage等
        cycleView.imageURLStringArr = ["banner01.jpg", "banner02.jpg", "banner03.jpg", "banner04.jpg", "banner05.jpg"]
        informationTableview.tableHeaderView = cycleView
        
        self.view.addSubview(informationTableview)
        
        self.informationTableview.register(UINib.init(nibName: "TCM_HomeInformationTableViewCell", bundle: nil), forCellReuseIdentifier: "InformationCell")
        return informationTableview
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if isClickedSegmented == false {
            let pageWidth = scrollView.frame.width
            let tmpPage = scrollView.contentOffset.x / pageWidth
            let tmpPage2 = scrollView.contentOffset.x / pageWidth
            let page = tmpPage2-tmpPage>=0.5 ? tmpPage+1 : tmpPage
            if startPage != Int(page) {
                self.segmentedControl.setSelectedSegmentIndex(index: Int(page), animated: true)
                startPage = Int(page)
            }
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let pageWidth = scrollView.frame.width
        let page = scrollView.contentOffset.x / pageWidth
        self.isClickedSegmented = false
        self.segmentedControl.setSelectedSegmentIndex(index: Int(page), animated: true)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 108
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = (informationTableview.dequeueReusableCell(withIdentifier: "InformationCell", for: indexPath)) as! TCM_HomeInformationTableViewCell
        cell.selectionStyle = .none
        
        cell.contentLabel.text = informationArry[0][indexPath.row]
        cell.typeLabel.text = informationArry[1][indexPath.row]
        cell.timeLabel.text = informationArry[2][indexPath.row]
        cell.readNumberLabel.text = informationArry[3][indexPath.row]
        
        cell.contentImageView.isHidden = false
        cell.contentImageView.image = UIImage.init(named: informationArry[4][indexPath.row])
        cell.contentLabelToViewtrailing.constant = 152
        
        return cell
    }
    
    // MARK: --cycleviewDelegate
    func cycleViewDidSelectedItemAtIndex(_ index: NSInteger) {
        print("点击了轮播图第\(index + 1)个图片")
        //        let demoVc = DemoController()
        //        demoVc.title = "点击了轮播图第\(index)个图片"
        //        demoVc.view.backgroundColor = UIColor.white
        //        navigationController?.pushViewController(demoVc, animated: true)
    }
}

